package com.example.weatherview.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.core.graphics.withRotation
import androidx.core.graphics.withTranslation
import kotlin.math.roundToInt

/**
 * @author Tom.wu
 * @Description:
 * @Package: com.example.weatherview.view
 * @data  2024/3/14 15:22
 */
class RamView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    companion object{
        const val MAX_ANGEL= 360F
    }


    private val mBgPaint  = Paint()

    private var mStrokeWidth = dp2Px(context,8F).toFloat()


    private val mData = arrayListOf(
        RamData(100,Color.parseColor("#5484FF")),
        RamData(80,Color.parseColor("#4DE4AE")),
        RamData(60,Color.parseColor("#2AC239")),
        RamData(50,Color.parseColor("#FF7A2F")),
        RamData(40,Color.parseColor("#FFC633"))
    )

    init {
        mBgPaint.apply {
            color = Color.parseColor("#D1D1D1")
            style = Paint.Style.STROKE
            strokeWidth = mStrokeWidth
            isAntiAlias = true
        }
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val w = MeasureSpec.getSize(widthMeasureSpec)
        val h = MeasureSpec.getSize(heightMeasureSpec)
        setMeasuredDimension(w,h)
    }

    private val mRectF = RectF()

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        val realW = w/2- mStrokeWidth / 2
        Log.d("Tom", "onSizeChanged: $realW")
        mRectF.apply {
            top = -realW
            left = -realW
            right = realW
            bottom = realW
        }
    }


    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.withTranslation(width/2f,height/2f){
            withRotation(-90f){
               drawArc(mRectF, 0f, MAX_ANGEL, false, mBgPaint)
                val ratio = MAX_ANGEL / mTotal
                val sortedByDescending = mData.sortedByDescending { it.value }
                sortedByDescending.forEach {
                    mBgPaint.color = it.color
                    drawArc(mRectF, 0f, ratio*it.value, false, mBgPaint)
                }
            }
        }
    }


    private var mTotal = 128

    fun setTotal(value: Int){
        mTotal = value
    }


    private fun dp2Px(context: Context, dp: Float): Int {
        val density = context.resources.displayMetrics.density
        return (dp * density).roundToInt()
    }
}

data class RamData(val value:Int,val color: Int)